<template>
  <n-form
    :model="formData"
    :rules="formRules"
    ref="formInstance"
    label-placement="left"
    label-width="80px"
  >
    <n-grid x-gap="12" :cols="1">
      <n-gi responsive="self">
        <n-form-item label="原密码" path="oldPassword">
          <n-input
            placeholder="请输入原密码"
            v-model:value="formData.oldPassword"
            type="password"
            clearable
          />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="新密码" path="newPassword">
          <n-input
            placeholder="请输入新密码"
            v-model:value="formData.newPassword"
            type="password"
            clearable
          />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="确认密码" path="confirmPassword">
          <n-input
            placeholder="请输入新密码"
            v-model:value="formData.confirmPassword"
            type="password"
            clearable
          />
        </n-form-item>
      </n-gi>
    </n-grid>
  </n-form>
</template>
<script lang="ts">
import { onMounted, reactive, ref } from 'vue';
import api from '@/api/loginApi';
import { FormInst } from 'naive-ui';
import { checkFormData } from '@/utils/formUtil';
import md5 from 'js-md5';

export default {
  props: {
    id: {
      type: [String, Number],
      default: null,
    },
    readMode: {
      type: [String],
      default: 'read',
    },
  },
  setup: function (props) {
    const formInstance = ref<FormInst | null>(null);
    const formData = ref<any>({
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    });
    const formRules = reactive({
      oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
      newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator(rule: any, value: string) {
            if (formData.value.newPassword && value && formData.value.newPassword === value) {
              return true;
            }
            return new Error('两次密码不一致');
          },
          trigger: 'blur',
        },
      ],
    });

    const doSubmit = async () => {
      await checkFormData(formInstance);
      let data: any = {};
      data.oldPassword = md5(formData.value.oldPassword);
      data.newPassword = md5(formData.value.newPassword);
      return api.doModifyPassword(data);
    };

    onMounted(() => {
      // init();
    });
    return {
      formData,
      formInstance,
      formRules,
      doSubmit,
    };
  },
};
</script>

<style lang="less" scoped></style>
